using Godot;
using System;

public partial class Client : Node
{
	[Export]
	public Game game;

	[Export]
	public PackedScene entityPrefab;

	[Export]
	public ChessRegistry registry;

    public override void _Ready()
    {
		Setup();
    }

	private void Setup()
	{
		SetupTeam(1, false);
		SetupTeam(0, true);
	}

	private void SetupTeam(int team, bool rev)
	{
		int Line(int l) => rev ? Rule.BOARD_ROW - l : l;
		var line1 = Line(0);
		var line3 = Line(2);
		var line4 = Line(3);

		SetChess(ChessType.Jv, team, 0, line1);
		SetChess(ChessType.Ma, team, 1, line1);
		SetChess(ChessType.Xiang, team, 2, line1);
		SetChess(ChessType.Shi, team, 3, line1);
		SetChess(ChessType.Jiang, team, 4, line1);
		SetChess(ChessType.Shi, team, Rule.ColOppsite(3), line1);
		SetChess(ChessType.Xiang, team, Rule.ColOppsite(2), line1);
		SetChess(ChessType.Ma, team, Rule.ColOppsite(1), line1);
		SetChess(ChessType.Jv, team, Rule.ColOppsite(0), line1);

		SetChess(ChessType.Pao, team, 1, line3);
		SetChess(ChessType.Pao, team, Rule.ColOppsite(1), line3);

		for (int i = 0; i <= Rule.BOARD_COL; i += 2)
			SetChess(ChessType.Zu, team, i, line4);
	}

	private void SetChess(ChessType ty, int team, int x, int y)
	{
		var entity = entityPrefab.Instantiate<Entity>();
		entity.team = team;
		entity.GetNode<Sprite2D>("Sprite2D").Texture = registry.GetChessTexture(ty, team);
		entity.entity = ty switch
		{	
			ChessType.Jiang => new Jiang(),
			ChessType.Shi => new Shi(),
			ChessType.Xiang => new Xiang(),
			ChessType.Ma => new Ma(),
			ChessType.Jv => new Jv(),
			ChessType.Pao => new Pao(),
			ChessType.Zu => new Zu(),
			_ => null,
		};
		game.SetEntity(x, y, entity);
	}
}
